package edu.ccut.saturn.studio.wfg.dialog.endactivitydialog;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;

import edu.ccut.saturn.studio.Activator;
import edu.ccut.saturn.studio.Images;
import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.wfg.dialog.RevertCandidate;
import edu.ccut.saturn.studio.wfg.dialog.SelectionCandidate;
import edu.ccut.saturn.studio.wfg.dialog.TableViewerContentProvider;
import edu.ccut.saturn.studio.wfg.dialog.vocationallogicdialog.LogicKeyAttributeLabelProvider;
import edu.ccut.saturn.studio.wfg.dialog.vocationallogicdialog.SaturnVocationalLogicDialogForAdd;
import edu.ccut.saturn.studio.wfg.dialog.vocationallogicdialog.SaturnVocationalLogicDialogForEdit;
import edu.ccut.saturn.studio.wfg.wfgmodel.LogicKeyAttribute;
import edu.ccut.saturn.studio.wfg.wfgmodel.SaturnAttribute;
import edu.ccut.saturn.studio.wfg.wfgmodel.SaturnEndNode;

public class SaturnEndActivityDialog extends TitleAreaDialog {
	
	private SaturnEndNode saturnEndNode;
	
	private LogicKeyAttribute logicKeyAttribute;
	
	private List<SaturnAttribute> logicKeyTemp;
	
	private TableViewer tableViewer;
	
	private Table table;
	
	private List<LogicKeyAttribute> keys = new ArrayList<LogicKeyAttribute>();
	
	private Text idText, nameText, descriptionText;
	
	private Combo comboMode;

	private Label idLabel, nameLabel, modeLabel, descriptionLabel;

	private Button addButton, deleteButton, upButton, downButton, editButton;

	public SaturnEndActivityDialog(Shell parentShell, SaturnEndNode saturnEndNode) {
		super(parentShell);
		this.saturnEndNode = saturnEndNode;
		this.copyLogicKeyList(saturnEndNode.getLogicList());
	}
	
	protected Control createContents(Composite parent) {
		Control contents = super.createContents(parent);
		setMessage(SelectionCandidate.SETTING_ATTRIBUTE + saturnEndNode.getName());
		return contents;
	}
	
	protected Control createDialogArea(Composite parent) {

		getShell().setText(SelectionCandidate.ATTRIBUTE_SETTING);
		Composite area = (Composite) super.createDialogArea(parent);
		setTitleImage(Activator.getImage(Images.SATURN_ICONS_MAXNAME));

		final Composite composite = new Composite(area, SWT.NONE);
		final GridData gd_composite = new GridData(SWT.FILL, SWT.FILL, false, false);
		gd_composite.heightHint = 180;
		gd_composite.widthHint = 358;
		composite.setLayoutData(gd_composite);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		composite.setLayout(gridLayout);
		
		idLabel = new Label(composite, SWT.NONE);
		final GridData gd_id = new GridData();
		gd_id.verticalIndent = 10;
		idLabel.setLayoutData(gd_id);
		idLabel.setText(Messages.getString("SaturnEndActivityDialog.ActionID"));   //$NON-NLS-1$
		
		idText = new Text(composite, SWT.BORDER | SWT.READ_ONLY);
		idText.setTextLimit(50);
		final GridData gd_idText = new GridData(SWT.FILL, SWT.CENTER, true, false);
		gd_idText.verticalIndent = 10;
		idText.setLayoutData(gd_idText);

		nameLabel = new Label(composite, SWT.NONE);
		final GridData gd_label = new GridData();
		gd_label.verticalIndent = 10;
		nameLabel.setLayoutData(gd_label);
		nameLabel.setText(Messages.getString("SaturnEndActivityDialog.ActionName"));   //$NON-NLS-1$

		nameText = new Text(composite, SWT.BORDER);
		nameText.setTextLimit(50);
		nameText.setFocus();
		final GridData gd_textName = new GridData(SWT.FILL, SWT.CENTER, true, false);
		gd_textName.verticalIndent = 10;
		nameText.setLayoutData(gd_textName);

		modeLabel = new Label(composite, SWT.NONE);
		final GridData gd_label_2 = new GridData();
		gd_label_2.verticalIndent = 10;
		modeLabel.setLayoutData(gd_label_2);
		modeLabel.setText(Messages.getString("SaturnEndActivityDialog.BindingPattern"));   //$NON-NLS-1$

		comboMode = new Combo(composite, SWT.NONE);
		final GridData gd_comboMode = new GridData(SWT.FILL, SWT.CENTER, true, false);
		gd_comboMode.verticalIndent = 5;
		comboMode.setLayoutData(gd_comboMode);
		comboMode.setItems(SelectionCandidate.polymeModeCandidate);

		descriptionLabel = new Label(composite, SWT.NONE);
		final GridData gd_label_3 = new GridData(SWT.LEFT, SWT.TOP, false, false);
		gd_label_3.verticalIndent = 10;
		descriptionLabel.setLayoutData(gd_label_3);
		descriptionLabel.setText(Messages.getString("SaturnEndActivityDialog.Description"));   //$NON-NLS-1$

		descriptionText = new Text(composite, SWT.V_SCROLL | SWT.BORDER);
		descriptionText.setTextLimit(200);
		final GridData gd_textDec = new GridData(SWT.FILL, SWT.FILL, true, true);
		gd_textDec.verticalIndent = 5;
		descriptionText.setLayoutData(gd_textDec);

		final Group logickeyGroup = new Group(area, SWT.NONE);
		logickeyGroup.setLayout(new FormLayout());
		logickeyGroup.setText("LogicKey"); //$NON-NLS-1$
		final GridData gd_logickeyGroup = new GridData(SWT.FILL, SWT.FILL, true, true);
		gd_logickeyGroup.verticalIndent = 10;
		gd_logickeyGroup.widthHint = 480;
		gd_logickeyGroup.heightHint = 185;
		logickeyGroup.setLayoutData(gd_logickeyGroup);

		tableViewer = new TableViewer(logickeyGroup, SWT.FULL_SELECTION | SWT.BORDER);
		table = tableViewer.getTable();
		final FormData fd_table = new FormData();
		fd_table.right = new FormAttachment(100, -85);
		fd_table.bottom = new FormAttachment(100,-5);
		fd_table.top = new FormAttachment(0, 5);
		fd_table.left = new FormAttachment(0, 5);
		table.setLayoutData(fd_table);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		tableViewer.setContentProvider(new TableViewerContentProvider());
		tableViewer.setLabelProvider(new LogicKeyAttributeLabelProvider());

		final TableColumn newColumnTableColumn = new TableColumn(table, SWT.NONE);
		newColumnTableColumn.setWidth(390);
		newColumnTableColumn.setText(Messages.getString("SaturnEndActivityDialog.Expression"));   //$NON-NLS-1$

		addButton = new Button(logickeyGroup, SWT.NONE);
		addButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				openAddDialog();
			}
		});
		final FormData fd_button = new FormData();
		fd_button.top = new FormAttachment(table, 0, SWT.TOP);
		fd_button.left = new FormAttachment(100, -70);
		fd_button.right = new FormAttachment(100, -15);
		addButton.setLayoutData(fd_button);
		addButton.setText(SelectionCandidate.INSERT_BUTTON);

		deleteButton = new Button(logickeyGroup, SWT.NONE);
		deleteButton.addSelectionListener(new SelectionAdapter() {
			@SuppressWarnings("unchecked") //$NON-NLS-1$
			public void widgetSelected(final SelectionEvent e) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
				logicKeyAttribute = (LogicKeyAttribute) selection.getFirstElement();
				if (selection.isEmpty()) {
					MessageDialog.openInformation(null, SelectionCandidate.HINT, SelectionCandidate.CHOOSE_DELETE_RECORD);
				} else {
					List<SaturnAttribute> logicKeyListForDelete = (List<SaturnAttribute>) tableViewer
							.getInput();
					logicKeyListForDelete.remove(logicKeyAttribute);
					tableViewer.setInput(logicKeyListForDelete);
				}
			}
		});
		final FormData fd_button_1 = new FormData();
		fd_button_1.top = new FormAttachment(addButton, 10, SWT.BOTTOM);
		fd_button_1.left = new FormAttachment(addButton, 0, SWT.LEFT);
		fd_button_1.right = new FormAttachment(addButton, 0, SWT.RIGHT);
		deleteButton.setLayoutData(fd_button_1);
		deleteButton.setText(SelectionCandidate.DELETE_BUTTON);

		upButton = new Button(logickeyGroup, SWT.NONE);
		upButton.addSelectionListener(new SelectionAdapter() {
			@SuppressWarnings("unchecked") //$NON-NLS-1$
			public void widgetSelected(final SelectionEvent e) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
				if (selection.isEmpty()) {
					MessageDialog.openInformation(null, SelectionCandidate.HINT, SelectionCandidate.CHOOSE_A_RECORD);
				} else {
					Table table_up = tableViewer.getTable();
					if (tableViewer.getTable() != null) {
						int i = table_up.getSelectionIndex();
						if (i > 0) {
							SaturnAttribute lka = logicKeyTemp.get(i);
							List<SaturnAttribute> logicKeyListForUp = (List<SaturnAttribute>) tableViewer.getInput();
							logicKeyListForUp.remove(lka);
							tableViewer.remove(lka);
							logicKeyListForUp.add(i - 1, lka);
							tableViewer.setInput(logicKeyListForUp);
							table_up.setSelection(i - 1);
						}
					}
				}
			}
		});
		final FormData fd_button_2 = new FormData();
		fd_button_2.top = new FormAttachment(deleteButton, 10, SWT.BOTTOM);
		fd_button_2.left = new FormAttachment(deleteButton, 0, SWT.LEFT);
		fd_button_2.right = new FormAttachment(deleteButton, 0, SWT.RIGHT);
		upButton.setLayoutData(fd_button_2);
		upButton.setText(SelectionCandidate.UP_BUTTON);

		downButton = new Button(logickeyGroup, SWT.NONE);
		downButton.addSelectionListener(new SelectionAdapter() {
			@SuppressWarnings("unchecked") //$NON-NLS-1$
			public void widgetSelected(final SelectionEvent e) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
				if (selection.isEmpty()) {
					MessageDialog.openInformation(null, SelectionCandidate.HINT, SelectionCandidate.CHOOSE_A_RECORD);
				} else {
					Table table_down = tableViewer.getTable();
					if (tableViewer.getTable() != null) {
						int i = table_down.getSelectionIndex();
						if (i < tableViewer.getTable().getItemCount() - 1){
							SaturnAttribute lka = logicKeyTemp.get(i);
							List<SaturnAttribute> logicKeyListForDown = (List<SaturnAttribute>) tableViewer
							.getInput();
							logicKeyListForDown.remove(lka);
							tableViewer.remove(lka);
							logicKeyListForDown.add(i + 1, lka);
							tableViewer.setInput(logicKeyListForDown);
							table_down.setSelection(i + 1);
						}
					}
				}
			}
		});
		final FormData fd_button_3 = new FormData();
		fd_button_3.top = new FormAttachment(upButton, 10, SWT.BOTTOM);
		fd_button_3.left = new FormAttachment(upButton, 0, SWT.LEFT);
		fd_button_3.right = new FormAttachment(upButton, 0, SWT.RIGHT);
		downButton.setLayoutData(fd_button_3);
		downButton.setText(SelectionCandidate.DOWN_BUTTON);

		editButton = new Button(logickeyGroup, SWT.NONE);
		editButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
				if (selection.isEmpty()) {
					MessageDialog.openInformation(null, SelectionCandidate.HINT, SelectionCandidate.CHOOSE_EDIT_RECORD);
				} else {
					logicKeyAttribute = (LogicKeyAttribute) selection.getFirstElement();
					
					openEditDialog(logicKeyAttribute);
					tableViewer.refresh();
				}
			}
		});
		final FormData fd_button_4 = new FormData();
		fd_button_4.top = new FormAttachment(downButton,10, SWT.BOTTOM);
		fd_button_4.left = new FormAttachment(downButton, 0, SWT.LEFT);
		fd_button_4.right = new FormAttachment(downButton, 0, SWT.RIGHT);
		editButton.setLayoutData(fd_button_4);
		editButton.setText(SelectionCandidate.EDIT_BUTTON);

		idText.setText(saturnEndNode.getId().trim());
		nameText.setText(saturnEndNode.getName().trim());
		comboMode.setText(RevertCandidate.revertPolymeMode(saturnEndNode.getPolymeMode().trim()));
		descriptionText.setText(saturnEndNode.getDescription().trim());
		tableViewer.setInput(logicKeyTemp);
		
		/**
		 * 活动名称不能为空
		 * 
		 * */
		nameText.addModifyListener(new ModifyListener() {
			public void modifyText(final ModifyEvent e) {
				if("".equals(nameText.getText().trim())){ //$NON-NLS-1$
					setErrorMessage(Messages.getString("SaturnEndActivityDialog.ActionNameCannotEmpty2"));   //$NON-NLS-1$
					getButton(IDialogConstants.OK_ID).setEnabled(false);
				} else {
					setErrorMessage(null);
					getButton(IDialogConstants.OK_ID).setEnabled(true);
				}
			}
		});
		
		return area;
	}
	
	protected void buttonPressed(int buttonId) {
		if (saturnEndNode == null) {
			return;
		}
		if (buttonId == IDialogConstants.OK_ID) {
			// 存到VO里
			saturnEndNode.setDescription(descriptionText.getText().trim());
			saturnEndNode.setName(nameText.getText().trim());
			saturnEndNode.setPolymeMode(RevertCandidate.revertFromFaceToVO(comboMode.getText().trim()));

			saturnEndNode.setLogicList(logicKeyTemp);
			}
		super.buttonPressed(buttonId);
	}
	
	@SuppressWarnings("unchecked") //$NON-NLS-1$
	private void openAddDialog(){
		SaturnVocationalLogicDialogForAdd addDialog = new SaturnVocationalLogicDialogForAdd(Display.getDefault().getShells()[0], logicKeyTemp, saturnEndNode);
		if (addDialog.open() == IDialogConstants.OK_ID) {
			tableViewer.setInput(logicKeyTemp);
		}
	}
	
	@SuppressWarnings("unchecked") //$NON-NLS-1$
	private void openEditDialog(LogicKeyAttribute logicKeyAttribute){
		SaturnVocationalLogicDialogForEdit editDialog = new SaturnVocationalLogicDialogForEdit(Display.getDefault().getShells()[0], logicKeyAttribute, saturnEndNode);
		editDialog.open();
	}

	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setImage(Activator.getImage(Images.SATURN_ICONS_SMALLNAME));
	}

	protected Point getInitialSize() {
		return new Point(500, 510);
	}
	
	private void copyLogicKeyList(List<SaturnAttribute> list){
		List<SaturnAttribute> logicKeyTemps = new ArrayList<SaturnAttribute>();
		
		for(SaturnAttribute saturn : list){
			LogicKeyAttribute logic = new LogicKeyAttribute((LogicKeyAttribute)saturn);
			logicKeyTemps.add(logic);
			keys.add(logic);
		}
		this.logicKeyTemp = logicKeyTemps;
		this.setKeys(keys);
	}
	
	protected int getShellStyle() {
		return SWT.CLOSE | SWT.RESIZE;
	}
	
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		super.createButtonsForButtonBar(parent);
		getButton(IDialogConstants.OK_ID).setEnabled(true);
	}

	public List<LogicKeyAttribute> getKeys() {
		return keys;
	}

	public void setKeys(List<LogicKeyAttribute> keys) {
		this.keys = keys;
	}
}
